import java.io.*;
import java.net.*;
public class Server5 {
    public static void main(String args[]) throws  IOException{
        String sharekey="";
        int n=-1;
        byte [] a=new byte[128];
        try{  File f=new File("key1.dat");
            InputStream in = new FileInputStream(f);
            while((n=in.read(a,0,100))!=-1) {
                sharekey=sharekey+new String (a,0,n);
            }
            in.close();
        }
        catch(IOException e) {
            System.out.println("File read Error"+e);
        }

        ServerSocket serverForClient=null;
        Socket socketOnServer=null;
        DataOutputStream out=null;
        DataInputStream  in=null;
        try { serverForClient = new ServerSocket(2010);
        }
        catch(IOException e1) {
            System.out.println(e1);
        }
        try{ System.out.println("等待客户呼叫");
            socketOnServer = serverForClient.accept(); //堵塞状态，除非有客户呼叫
            out=new DataOutputStream(socketOnServer.getOutputStream());
            in=new DataInputStream(socketOnServer.getInputStream());
            String keyone =in.readUTF();//读取被DH算法加密的密钥
            String truekey = Encoder.AESDncode(sharekey,keyone);//使用共享密钥对被加密的原密钥解密。
            String secret =in.readUTF(); // in读取信息，堵塞状态
            System.out.println("服务器收到的信息:"+secret);
            String mdClient=in.readUTF();
            System.out.println("客户端提供的MD5为:"+ mdClient);
            String clear = Encoder.AESDncode(truekey,secret);//使用原密钥解密表达式
            Float answer=MyDC.calrp(clear);
            if((mdClient.equals(DigestPass.MD5(clear)))==true) {//判断MD5值是否相等，若相等，则返回答案
                System.out.println("MD5值匹配");
                System.out.println("服务器提供的解密:" + clear);
                System.out.println("服务器解出密文的MD5为:" + DigestPass.MD5(clear));
                out.writeUTF(answer + "");
            }
            Thread.sleep(500);
        }
        catch(Exception e) {
            System.out.println("客户已断开"+e);
        }
    }
}
